#include"../tcpserver.hpp"

class EchoServer
{
public:
    EchoServer(int port)
        :_server(port)
    {
        _server.set_server_threadpool_num(2);
        _server.set_server_connect_cb([this](const ConnectionPtr& conn){this->echo_connect(conn);});
        _server.set_server_msg_cb([this](const ConnectionPtr& conn,InBuffer* inbuff){this->echo_message(conn,inbuff);});
        _server.set_server_close_cb([this](const ConnectionPtr& conn){this->echo_close(conn);});
    }

    void start()
    {
        _server.Start();
    }


private:
    void echo_connect(const ConnectionPtr& conn)
    {
        DBG("one connected! peer addr is %s, local socket fd is %d",conn->get_socket_addr(),conn->get_connid());
    }

    void echo_message(const ConnectionPtr& conn,InBuffer* inbuff)
    {
        const char* msg=inbuff->get_from_buff();
        std::string msg_str(msg,msg+inbuff->length());
        inbuff->pop(inbuff->length());
        inbuff->adjust();

        DBG("socket fd %d recv message:%s",conn->get_connid(),msg_str.c_str());

        conn->send(msg_str.c_str(),msg_str.length());
    }

    void echo_close(const ConnectionPtr& conn)
    {
        DBG("one connection closed in echo server!");
    }


private:
    TcpServer _server;
};


int main()
{
    Log::get_instance()->init(nullptr);

    Log::get_instance()->set_log_level(Log::DEBUG_LOG_LEVEL);

    EchoServer server(8888);

    server.start();

    return 0;
}